require 'byebug'

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :update, :destroy]

  # GET /books
  # def index
  #   @books = Book.all
  #   render json: @books
  # end
  def index
    @books = Book.page(params[:page]).per(params[:per_page] || 10)

    render json: {
      books: @books,
      meta: {
        current_page: @books.current_page,
        total_pages: @books.total_pages,
        total_count: @books.total_count
      }
    }
  end

  # GET /books/1
  def show
    render json: @book
  end

  # GET /books/show2/1
  def show2
    # # 路径参数: 根据id查询book
    @book = Book.find(params[:id])
    render json: @book
  end

  # GET /books/search?title=xxx
  def search
    # 调试代码
    # binding.pry
    # 查询参数
    @books = Book.where('title LIKE ?', "%#{params[:title]}%")
    # 返回查询的book
    render json: @books
  end

  # POST /books
  def create
    @book = Book.new(book_params)

    if @book.save
      render json: @book, status: :created
    else
      render json: @book.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /books/1
  def update
    if @book.update(book_params)
      render json: @book
    else
      render json: @book.errors, status: :unprocessable_entity
    end
  end

  # DELETE /books/1
  def destroy
    @book.destroy
    head :no_content
  end

  private
  def set_book
    # 调试代码
    # binding.pry
    @book = Book.find(params[:id])
  end

  def book_params
    params.require(:book).permit(:title, :author, :published_year)
  end
end
